const express = require("express");
const router = express.Router();
const { userModel } =  require('../model/user');
const env = require('dotenv').config().parsed;
const jwt = require('jsonwebtoken');
/* GET users listing. */
router.post("/login", async(req, res) =>{
  const { _id, username, password, phone } =  req.body
  let user =  phone ? await userModel.findOne({ phone }) :
    await userModel.findOne({ username })
  if (!user) {
    // 这里假设phone也是必填项，用于创建新用户
    await userModel.create({ username, password });
    user = await userModel.findOne({ username });
  }
  const accessToken = jwt.sign({ _id: user._id }, process.env.ACCESS_TOKEN_SECRET, { expiresIn: Math.floor(Date.now() / 1000) + Number(process.env.ACCESS_TOKEN_EXPIRES_IN) });
  const refreshToken = jwt.sign({ _id: user._id }, process.env.REFRESH_TOKEN_SECRET, { expiresIn: Math.floor(Date.now() / 1000) + Number(process.env.REFRESH_TOKEN_EXPIRES_IN) });
  if ( user && user.password !== password) {
    return res.status(401).json({ code: 401,message: '密码错误',status: "error" })
  } else {
    return res.status(200).json({
      code: 200,
      message: "登录成功",
      status: "success",
      result: {
        access_token:accessToken,
        refresh_token:refreshToken,
        expiresIn: Math.floor(Date.now() / 1000) + Number(process.env.ACCESS_TOKEN_EXPIRES_IN),
        user
      },
    })
  }
})

router.post('/refresh-token', async (req, res) => {
  const { refresh_token, expiresIn } = req.body

  const decodedRefreshToken = jwt.verify ( refresh_token, process.env.REFRESH_TOKEN_SECRET );
  const user = await userModel.findById ( decodedRefreshToken._id );
  jwt.verify ( refresh_token, process.env.REFRESH_TOKEN_EXPIRES_IN, ( err, decodedRefreshToken ) => {
    if (err) {
      return res.status(403).json({ code: 401,message: '登录过期，请重新登录',status: "error" })
    }
    const accessToken = jwt.sign({ _id: decodedRefreshToken._id }, process.env.ACCESS_TOKEN_SECRET, { expiresIn: Math.floor(Date.now() / 1000) + Number(process.env.ACCESS_TOKEN_EXPIRES_IN) });
    return   res.status(200).json({
      code: 200,
      message: "Token刷新成功",
      status: "success",
      result: {
        expiresIn,
        access_token: accessToken,
      },
    })
  })
})

router.get("/", function (req, res, next) {

  res.send({
    code: 200,
    message: "获取成功",
    status: "success",
    result: {
      name: "张三",
      age: 18,
      sex: "男",
    },
  });
});
module.exports = router;
